package dao

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
)

// http path
const (
	boxIPPath = "/api/v1/resource_center/box/ip"
)

type boxIPResp struct {
	ReturnCode   int    `json:"returnCode"`
	ErrorMessage string `json:"errorMessage"`
	Result       string `json:"result"`
}

// GetBoxIP get box ip
func (d *Dao) GetBoxIP(ctx context.Context) (string, error) {

	resResp := new(boxIPResp)

	resp, err := d.http().R().SetContext(ctx).Get(d.resCenterHost + boxIPPath)
	if err != nil {
		return "", fmt.Errorf("HTTP request err: %s", err)
	}

	if resp.StatusCode() != http.StatusOK {
		return "", fmt.Errorf("HTTP status %s", resp.Status())
	}

	if err := json.Unmarshal(resp.Body(), resResp); err != nil {
		return "", err
	}

	if resResp.ReturnCode != 0 {
		return "", fmt.Errorf("Errcode: %d, Msg: %s", resResp.ReturnCode, resResp.ErrorMessage)
	}

	return resResp.Result, nil
}
